package com.hzit.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzit.model.FloatPrice;
import com.hzit.model.Goods;
import com.hzit.model.Msg;
import com.hzit.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller

public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    //添加商品
    @RequestMapping("/goods/add")
    @ResponseBody
    public Object add(@RequestBody Goods goods){
        goods.setUserId(2); //TODO 需要从登录传来userId
        Date date = new Date();
        goods.setCreateTime(date);
        goods.setUpdateTime(date);
        boolean save = goodsService.save(goods);
        if(save){
            return new Msg("200","添加成功");
        }else{
            return new Msg("500","添加失败");
        }
    }
    //修改商品
    @RequestMapping("update")
    @ResponseBody
    public Object update(@RequestBody Goods goods){
        Date date = new Date();
        goods.setUpdateTime(date);
        boolean save = goodsService.updateById(goods);
        if(save){
            return new Msg("200","修改成功");
        }else{
            return new Msg("500","修改失败");
        }
    }
    //删除商品（逻辑删除，状态由1变为0）
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Integer id){

        Goods goods = new Goods();
        goods.setStatus(0);
        goods.setId(id);
        // boolean save = goodsService.removeById(id); remove是真正删除
        boolean save = goodsService.updateById(goods);
        if(save){
            return new Msg("200","删除成功");
        }else{
            return new Msg("500","删除失败");
        }
    }

    /**
     * 判断输入的价格是否在浮动范围之内
     *      1、首先要获取商品
     *      2、获取商品的参考价格
     *      3、获取商品的浮动价格
     * @return
     */
    @RequestMapping("isFloat")
    @ResponseBody
    public Object isFloat(Integer goodsId,Integer price) throws Exception{
        //根据商品id查询商品
        Goods goods = goodsService.getById(goodsId);
        //获取浮动价格{}
        String floatPrice = goods.getFloatPrice();

        //将前端的json对象转换为实体类
        ObjectMapper objectMapper = new ObjectMapper();
        FloatPrice floatPrice1 = objectMapper.readValue(floatPrice, FloatPrice.class);

        //获取参考价格
        Integer price1 = goods.getPrice();

        if( price < floatPrice1.getTop()+price1 && price > price1-floatPrice1.getDown()){
            return new Msg("200","价格设置合理");
        }else {
            return new Msg("400","价格处于范围之外");
        }
    }
}

